package com.example.zhu.controller;

import com.example.zhu.dto.R;
import com.example.zhu.dto.Student;
import com.example.zhu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentservice;

    @Transactional
    @GetMapping
    public R<Student> getId() {
        Student student = studentservice.getstudent();
        if (student != null) {
            Student student1 = new Student();
            student1.setId(student.getId());
            student1.setState(2);
            studentservice.updateData(student1);
            System.out.println("现在的数据是：" + student.toString());
            return R.success(student);
        }
        return R.error("没有数据了");
    }

    @Transactional
    @GetMapping("/amend/{id}")
    public R<String> completeCourse(@PathVariable("id") String id) {
        if (id != null) {
            Student student = new Student();
            student.setId(id);
            student.setState(1);
            studentservice.updateData(student);
            System.out.println("修改的数据是：" + student.toString());
            return R.success("修改成功");
        }
        return R.error("修改失败");

    }

    @Transactional
    @GetMapping("/add")
    public R<String> getStudent(Student student) {
        student.setState(0);
        try {
            studentservice.save(student);
        } catch (Exception e) {
            return R.error("添加失败，学号重复");
        }
        return R.success("添加成功");
    }


}
